package com.glory.dgcpcpda.activity;

import android.Manifest;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.content.Context;

import androidx.annotation.NonNull;

import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.base.Constant;
import com.glory.dgcpcpda.base.MyApp;
import com.glory.dgcpcpda.entity.AuthorityListEntity;
import com.glory.dgcpcpda.entity.LoginEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_BaseActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_PasswordEditText;

import java.io.File;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * FileName: LoginActivity
 * Author: XJH
 * Date: 2020/5/12 10:45
 * Description: 登录界面
 * History:
 */
public class LoginActivity extends FreeUI_BaseActivity implements EasyPermissions.PermissionCallbacks {
    @BindView(R.id.ivSetting)
    ImageView ivSetting;
    @BindView(R.id.etUser)
    FreeUI_ClearEditText etUser;
    @BindView(R.id.etPassword)
    FreeUI_PasswordEditText etPassword;
    @BindView(R.id.btnLogin)
    Button btnLogin;

    private static final int PERMISSIONS_REQUEST_CODE = 10;
    private int code;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        Constant.REQUEST_URL_DEBUG = FreeApi_SharePreferencesUtils.getSharePre("DG_CPC_FILE", "REQUEST_URL_DEBUG", Constant.REQUEST_URL_DEBUG, MyApp.app);
        //Constant.REQUEST_MES = FreeApi_SharePreferencesUtils.getSharePre("DG_CPC_FILE", "REQUEST_MES", Constant.REQUEST_MES, MyApp.app);
        Constant.REQUEST_CPC = FreeApi_SharePreferencesUtils.getSharePre("DG_CPC_FILE", "REQUEST_CPC", Constant.REQUEST_CPC, MyApp.app);
        Constant.FILE_URL = FreeApi_SharePreferencesUtils.getSharePre("DG_CPC_FILE", "FILE_URL_DEBUG", Constant.FILE_URL, MyApp.app);
        Constant.CURRENT_USER = FreeApi_SharePreferencesUtils.getSharePre("DG_CPC_FILE", "CURRENT_USER", MyApp.app);
        Constant.PRINTER_ADDR = FreeApi_SharePreferencesUtils.getSharePre("DG_CPC_FILE", "PRINTER_ADDR", MyApp.app);
        etUser.setText(Constant.CURRENT_USER);
    }


    @Override
    protected void initData() {
        //删除日志
        deleteOldLogs();
        requestPermission();
        //比对版本
        detectionUpdate();
    }

    private void clear() {
        SharedPreferences sharedPreferences = getSharedPreferences("DG_CPC_FILE", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.clear();
        edit.commit();
    }

    private void getPermission(String userName) {
        FreeUI_EntityCallBack<BaseResponseBean<AuthorityListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AuthorityListEntity>>
                (new TypeToken<BaseResponseBean<AuthorityListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<AuthorityListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    Constant.AUTHORITY_ENTITY = response.body().getResponse().getBody();
                    if (Constant.AUTHORITY_ENTITY != null) {
                        FreeApi_SharePreferencesUtils.setSharePre("DG_CPC_FILE", "CURRENT_USER", etUser.getText().toString().trim(), getApplicationContext());
                        showToast("登陆成功", true);
                        FreeApi_Utils.skipWithExtraIntent("", LoginActivity.this, MainActivity.class);
                        finish();
                    } else {
                        showToast("当前登录人员无任何权限!", false);
                    }

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AuthorityListEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "USER_GETAUTHORITY");
            }
        };

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("NAME", userName);
        jsonObject.addProperty("AUTHORITYCATEGORY", "PDA");
        NetUtils.requestPostNet("SYS.USER_GETAUTHORITY", "USER_GETAUTHORITY", this, jsonObject, callBack);
//        NetUtils.requestMESPostNet("SYS.USER_GETAUTHORITY", this, jsonObject, callBack);

    }

    private void detectionUpdate() {
        PackageManager manager = getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = info.versionName;
        FreeUI_EntityCallBack<FreeUI_VersionEntity> callBack = new FreeUI_EntityCallBack<FreeUI_VersionEntity>
                (new TypeToken<FreeUI_VersionEntity>() {
                }.getType()) {

            @Override
            public void onSuccess(Response<FreeUI_VersionEntity> response) {
                FreeUI_VersionEntity entity = response.body();
                entity.setCurrentVersion(version);
                code = compareVersion(version, entity.getVersion());
                Toast.makeText(LoginActivity.this, version+"/"+entity.getVersion(), Toast.LENGTH_SHORT).show();
                if(code == -1 ||code == 1) {
                    FreeUI_DownloadFragmentDialog downloadFragmentDialog = new FreeUI_DownloadFragmentDialog();
                    downloadFragmentDialog.setData(entity);
                    downloadFragmentDialog.show(getSupportFragmentManager(), "DOWNLOAD");
                }

            }

            @Override
            public void onError
                    (Response<FreeUI_VersionEntity> response) {
                super.onError(response);
            }
        };
        Map<String, String> map = new HashMap<>();
        FreeApi_NetUtils.requestGetNet(Constant.FILE_URL, this, map, callBack);
    }

    private void deleteOldLogs() {
        File logsDir = new File(Environment.getExternalStorageDirectory(), "/crash");
        if (!logsDir.exists()) {
            // 如果日志目录不存在，则无需进行任何操作
            return;
        }
        File[] files = logsDir.listFiles();
        if (files != null){
            for (File file : files){
                String fileName = file.getName();
                if (fileName.startsWith("crash") && fileName.endsWith(".log")){
                    String dateStr = fileName.substring(5, 15); // 提取日期部分
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                        Date fileDate = sdf.parse(dateStr);
                        long diff = System.currentTimeMillis() - fileDate.getTime();

                        // 转换为天数
                        long daysDiff = diff / (1000 * 60 * 60 * 24);

                        if (daysDiff >= 15) {
                            // 如果文件超过15天，则删除
                            file.delete();
                        }
                    } catch (Exception e) {
                        // 日期解析失败或其他异常处理
                        // 可以在这里添加日志或其他处理
                    }
                }
            }
        }
    }

    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        } else {
            String[] version1Array = version1.split("\\.");
            String[] version2Array = version2.split("\\.");
            Log.d("HomePageActivity", "version1Array==" + version1Array.length);
            Log.d("HomePageActivity", "version2Array==" + version2Array.length);
            int index = 0;
            int minLen = Math.min(version1Array.length, version2Array.length);
            int diff = 0;
            Log.d("HomePageActivity", "verTag2=2222=" + version1Array[index]);

            while (index < minLen && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) {
                ++index;
            }

            if (diff == 0) {
                int i;
                for (i = index; i < version1Array.length; ++i) {
                    if (Integer.parseInt(version1Array[i]) > 0) {
                        return 1;
                    }
                }

                for (i = index; i < version2Array.length; ++i) {
                    if (Integer.parseInt(version2Array[i]) > 0) {
                        return -1;
                    }
                }

                return 0;
            } else {
                return diff > 0 ? 1 : -1;
            }
        }
    }

    @AfterPermissionGranted(PERMISSIONS_REQUEST_CODE)
    private void requestPermission() {
        //Manifest.permission.READ_PHONE_STATE 申请不到
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
        //权限判断，第一次弹出系统的授权提示框
        if (EasyPermissions.hasPermissions(this, perms)) {
            //@AfterPermissionGranted 有权限直接执行 todo...
            //login();
        } else {
            //没有权限的话，先提示，点确定后弹出系统的授权提示框
            EasyPermissions.requestPermissions(this, "程序运行需要权限",
                    PERMISSIONS_REQUEST_CODE, perms);
        }
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return null;
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        showToast("用户授权失败", false);
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @OnClick({R.id.ivSetting, R.id.btnLogin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivSetting:
                FreeApi_Utils.skipWithExtraIntent("header", LoginActivity.this, SettingActivity.class);
                break;
            case R.id.btnLogin:
                if (etUser.getText().toString().trim().length() == 0) {
                    showToast("请输入用户名", false);
                    return;
                }

                if (etPassword.getText().toString().trim().length() == 0) {
                    showToast("请输入密码", false);
                    return;
                }

                login();
                break;
        }
    }

    private void login() {
        FreeUI_EntityCallBack<BaseResponseBean<LoginEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<LoginEntity>>
                (new TypeToken<BaseResponseBean<LoginEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LoginEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
//                    //权限获取
                    Constant.CURRENT_USER = response.body().getResponse().getBody().getUSER().getUSERNAME();
                    Constant.CURRENT_DESC = response.body().getResponse().getBody().getUSER().getDESCRIPTION();
                    getPermission(response.body().getResponse().getBody().getUSER().getUSERNAME());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LoginEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "USER_LOGIN");
            }
        };

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("USERNAME", etUser.getText().toString().trim());
        jsonObject.addProperty("PASSWORD", etPassword.getText().toString().trim());
        jsonObject.addProperty("ACTIONTYPE", "LOGIN");
        jsonObject.addProperty("MACADRR", getLocalMacAddressFromIp());
        NetUtils.requestPostNet("SYS.USER_LOGIN", "USER_LOGIN", this, jsonObject, callBack);
//        NetUtils.requestMESPostNet("SYS.USER_LOGIN", this, jsonObject, callBack);

//        FreeApi_SharePreferencesUtils.setSharePre("DG_CPC_FILE", "CURRENT_USER", etUser.getText().toString().trim(), getApplicationContext());
//        showToast("登陆成功", true);
//        FreeApi_Utils.skipWithExtraIntent("", LoginActivity.this, MainActivity.class);
//        finish();
    }

    /**
     * 根据IP地址获取MAC地址
     * @return
     */
    private static String getLocalMacAddressFromIp() {
        String strMacAddr = null;
        try {
            //获得IpD地址
            InetAddress ip = getLocalInetAddress();
            byte[] b = NetworkInterface.getByInetAddress(ip).getHardwareAddress();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < b.length; i++) {
                if (i != 0) {
                    buffer.append(':');
                }
                String str = Integer.toHexString(b[i] & 0xFF);
                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddr = buffer.toString().toUpperCase();
        } catch (Exception e) {
        }
        return strMacAddr;
    }
    /**
     * 获取移动设备本地IP
     * @return
     */
    private static InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            //列举
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {//是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();//得到下一个元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();//得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }
                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ip;
    }
}
